<?php

namespace App\Console\Commands\Tools\Camera;

use App\Kuafu\Shop\Jobs\SyncCameraJob;
use App\Kuafu\Shop\Model\CameraModel;
use App\Kuafu\Shop\Model\Shop;
use App\Kuafu\Shop\Model\ShopMonitorDataHourModel;
use App\Kuafu\Shop\Model\ShopMonitorDataModel;
use App\Kuafu\Shop\Service\CameraLibrary\CameraFactory;
use App\Kuafu\Shop\Service\CameraService;
use App\Kuafu\Shop\Service\ShopService;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;

class FetchCameraStatus extends Command
{
    protected $signature   = 'tools:fetch-camera-status';
    protected $description = '摄像头的列表数据查询';

    public function handle()
    {
        $this->exportAllData();
    }


    private function exportAllData()
    {
        $shopList = Shop::query()
                        ->where('status', 0)
//                        ->where('id', 13112)
                        ->get();

        $allList = [];
        foreach ($shopList as $shopInfo) {
            $list = CameraService::getCameraList($shopInfo->id);

            if (count($list) > 0) {
                // 批量获取摄像头状态
                $first                 = $list[0];
                $camera                = new CameraFactory($first->id);
                $cameraStatusListCache = Cache::remember('getDeviceStatusBatch:' . $shopInfo->id, 7200,
                    function () use ($camera, $list) {
                        return $camera->getIns()->getDeviceStatusBatch($list->toArray());
                    });
//                $cameraStatusList = $camera->getIns()->getDeviceStatusBatch($list->toArray());
                $cameraStatusList = array_column($cameraStatusListCache, null, 'id');

                foreach ($list as &$item) {
                    $item['status'] = $cameraStatusList[$item['id']]['status'] ?? 0;

                    $allList[] = [
                        'shopId'             => $shopInfo->id,
                        'shopCode'           => $shopInfo->shopCode,
                        'shopName'           => $shopInfo->name,
                        'cameraSupplierText' => CameraModel::SUPPLIER_TEXT[$shopInfo->cameraSupplier] ?? '',
                        'cameraName'         => $item->name,
                        'status'             => $item['status'] == 0 ? '离线' : '在线',
                        'checkTime'          => date('Y-m-d H:i:s')
                    ];
                }
            }

            $this->info($shopInfo->id . ':' . $shopInfo->name . '摄像头状态获取完成');
        }

        $csvData = '门店 Id,门店编号,门店名称,提供方,摄像头名称,状态,检查时间' . PHP_EOL;
        foreach ($allList as $item) {
            $csvData .= implode(',', $item) . PHP_EOL;
        }

        file_put_contents(storage_path('./camera_status.csv'), $csvData);

    }


}
